<template>
  <a-spin :loading="loading" style="width: 100%">
    <a-form ref="formRef" :model="formModel">
      <a-form-item field="pay_method" label="支付方式" label-col-flex="100px">
        <a-radio-group v-model="formModel.pay_method">
          <a-radio v-for="(item, index) in payments" :key="index" :value="index">{{ item }}</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        field="mch_id"
        label="商户号"
        label-col-flex="100px"
        required
        :rules="[
          { required: true, message: '商户号不能为空' }
        ]"
      >
        <a-input v-model="formModel.mch_id" placeholder="" style="width: 40%"/>
      </a-form-item>
      <a-form-item
        field="app_id"
        label="应用ID"
        label-col-flex="100px"
        required
        :rules="[
          { required: true, message: '应用ID不能为空' }
        ]"
      >
        <a-input v-model="formModel.app_id" placeholder="" style="width: 40%"/>
      </a-form-item>
      <a-form-item
        field="app_secret"
        label="秘钥"
        label-col-flex="100px"
        required
        :rules="[
          { required: true, message: '秘钥不能为空' }
        ]"
      >
        <a-input v-model="formModel.app_secret" placeholder="" style="width: 40%"/>
      </a-form-item>
      <a-form-item label="" label-col-flex="100px">
        <a-space>
          <a-button type="primary" @click="submit">
            <icon-send /> 保存
          </a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { FormInstance } from '@arco-design/web-vue/es/form';

  import useLoading from '@/hooks/loading';
  import { apiPaymentConfig } from '@/api/setting';

  const { loading, setLoading } = useLoading(true);
  const baseFormModel = {
    pay_method: 'wxpay',
    mch_id: '',
    app_id: '',
    app_secret: '',
  };
  const formRef = ref<FormInstance>();
  const formModel = ref<any>(baseFormModel);

  const payments = ref<any>([]);

  const fetchData = async () => {
    try {
      const { data } = await apiPaymentConfig();
      payments.value = data.payments;
      if (data.config) {
        formModel.value = data.config;
      }
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  // 提交
  const submit = async () => {
    try {
      const ruleRes = await formRef.value?.validate();
      if (!ruleRes) {
        setLoading(true);
        await apiPaymentConfig(formModel.value, 'post');
      }
    } catch (err) {
      setLoading(false);
    } finally {
      setLoading(false);
    }
  };

  fetchData();
</script>

<style scoped lang="less"></style>
